package com.openvalley.cyj.migration.slice;

import com.openvalley.cyj.migration.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.IAbilityContinuation;
import ohos.aafwk.ability.continuation.*;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.IntentParams;
import ohos.agp.components.Text;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

public class MainAbilitySlice extends AbilitySlice implements IAbilityContinuation {
    private static final HiLogLabel LABEL_LOG = new HiLogLabel(HiLog.LOG_APP, 0x00001, MainAbilitySlice.class.getSimpleName());

    Text text_register = null;
    Text text_show = null;
    Text text_startMigration = null;
    Text text_showParams = null;
    Text text_returnMigration = null;

    IContinuationRegisterManager continuationRegisterManager = null;
    IContinuationDeviceCallback continuationDeviceCallback = null;
    RequestCallback requestCallback = null;
    String jsonParams = null;
    int abilityToken = 0;
    String deviceId = null;

    String params = null;
    boolean isMigration = false;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        initContinuationRegisterManager();
        initComponent();
    }

    /**
     * 初始化注册管理类
     */
    private void initContinuationRegisterManager(){
       continuationRegisterManager = getContinuationRegisterManager();
       //设备的回调（是在列出了设备列表后，选择某个设备进行流转连接成功或者断开时调用）
       continuationDeviceCallback = new IContinuationDeviceCallback() {
           @Override
           public void onConnected(ContinuationDeviceInfo deviceInfo) {
               HiLog.info(LABEL_LOG, "onConnected()");
               deviceId = deviceInfo.getDeviceId();
               HiLog.info(LABEL_LOG, "onConnected() 连接成功。 deviceId = " + deviceId);
               continuationRegisterManager.updateConnectStatus(abilityToken, deviceId, DeviceConnectState.CONNECTED.getState(), requestCallback);
           }

           @Override
           public void onDeviceConnectDone(String s, String s1) {
               HiLog.info(LABEL_LOG, "onDeviceConnectDone()");
           }

           @Override
           public void onDisconnected(String deviceId) {
               HiLog.info(LABEL_LOG, "onDisconnected()");
           }

           @Override
           public void onDeviceDisconnectDone(String s) {
               HiLog.info(LABEL_LOG, "onDeviceDisconnectDone()");
           }
       };
       //请求的回调（注册到服务中心成功）
        requestCallback = new RequestCallback() {
            @Override
            public void onResult(int i) {
                if(i > 0){
                    //为了保证更新数据时这个值还在，所以在if里写
                    abilityToken = i;
                    HiLog.info(LABEL_LOG, "onResult() 注册成功。 abilityToken = " + abilityToken);
                }else {
                    HiLog.info(LABEL_LOG, "onResult() 其他操作。 abilityToken = " + i);
                }
            }
        };
    }

    /**
     * 初始化组件
     */
    private void initComponent(){
        text_register = (Text)findComponentById(ResourceTable.Id_text_register);
        text_register.setClickedListener(listen -> register());

        text_show = (Text)findComponentById(ResourceTable.Id_text_show);
        text_show.setClickedListener(listen -> show());

        text_startMigration = (Text)findComponentById(ResourceTable.Id_text_startMigration);
        text_startMigration.setClickedListener(listen -> startMigration());

        text_showParams = (Text)findComponentById(ResourceTable.Id_text_showParams);
        text_showParams.setText("这里展示数据：" + params);

        text_returnMigration = (Text)findComponentById(ResourceTable.Id_text_returnMigration);
        text_returnMigration.setClickedListener(listen -> returnMigration());
    }

    /**
     * 点击按钮进行流转服务注册
     */
    private void register(){
        if(continuationRegisterManager != null){
            HiLog.info(LABEL_LOG, "register() 开始注册。");
            continuationRegisterManager.register(getBundleName(), getExtraParams(), continuationDeviceCallback, requestCallback);
        }
    }

    /**
     * 展示可流转的设备
     */
    private void show(){
        if(continuationRegisterManager != null && abilityToken > 0){
            continuationRegisterManager.showDeviceList(abilityToken, getExtraParams(), requestCallback);
        }
    }

    /**
     * 开始迁移
     */
    private void startMigration(){
        if(continuationRegisterManager != null && deviceId != null){
            HiLog.info(LABEL_LOG, "startMigration() 开始迁移。");
//            continueAbility(deviceId);
            continueAbilityReversibly(deviceId);
            isMigration = true;
            HiLog.info(LABEL_LOG, "startMigration() 迁移结束。");
            //如果是不回迁的，这边的页面就可以销毁掉
//            terminateAbility();
        }
    }

    /**
     * 迁移回原设备
     */
    private void returnMigration(){
//        ContinuationState.
        try{
            boolean reverseContinueAbility = reverseContinueAbility();
            HiLog.info(LABEL_LOG, "reverseContinueAbility = " + reverseContinueAbility);
            isMigration = false;
        }catch (Exception e){
            HiLog.info(LABEL_LOG, "e = " + e.getMessage());
        }
    }

    /**
     * 获得注册时 额外的一些参数
     * @return
     */
    private ExtraParams getExtraParams(){
        ExtraParams extraParams = new ExtraParams();
        String[] devType = {ExtraParams.DEVICETYPE_SMART_PHONE, ExtraParams.DEVICETYPE_SMART_PAD};
        //显示的列表包含那些设备类型
        extraParams.setDevType(devType);
        //添加描述（没出来）
        extraParams.setDescription("这是一个描述。");
        //如果不写，就会默认以注册时的BundleName作为targetBundleName
        extraParams.setTargetBundleName(getBundleName());
        //设备过滤
        jsonParams = "\"{" +
                        "\"filter\":{" +
                            "\"commonFilter\":{" +
                                "\"system\":{" +
                                    //目标设备对应的HarmonyOS版本 要≥
                                    "\"harmonyVersion\":\"2.0.0\"" +
                                "}," +
//                                "}" +
                                //1为同账号，1|256为不同账号
                                "\"groupType\":\"1|256\"," +
                                //0x00000004需要在同一局域网下，0x00030004不需要在同一局域网下
                                "\"curComType\": 0x00030004," +
                                //为空就不做版本兼容性检查，要做版本兼容性检查时，需要传入目标应用包名。
                                "\"faFilter\":\"{" +
                                    "\"targetBundleName\":\"com.openvalley.cyj.migration\"" +
                                "}\"" +
                            "}" +
                        "}," +
                        "\"transferScene\":0," +
                        "\"remoteAuthenticationDescription\": \"拉起HiVision扫描弹框描述\"" +
                    "}\"";
//        HiLog.info(LABEL_LOG, jsonParams);
        extraParams.setJsonParams(jsonParams);
        return extraParams;
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onStop() {
        if(continuationRegisterManager != null && abilityToken > 0){
            continuationRegisterManager.unregister(abilityToken, requestCallback);
        }
    }

    /**
     * 准备开始迁移的回调
     * @return
     */
    @Override
    public boolean onStartContinuation() {
        //返回值为true才发起迁移
        HiLog.info(LABEL_LOG, "MainAbilitySlice onStartContinuation");
        return true;
    }

    /**
     * 当保存数据（要迁移的数据）的回调
     * @param intentParams
     * @return
     */
    @Override
    public boolean onSaveData(IntentParams intentParams) {
        HiLog.info(LABEL_LOG, "MainAbilitySlice onSaveData");
        intentParams.setParam("userName", "陈依劼");
        return true;
    }

    /**
     * 当恢复数据的回调（应该是被迁移的设备调用
     * @param intentParams
     * @return
     */
    @Override
    public boolean onRestoreData(IntentParams intentParams) {
        //返回为true代表恢复数据成功
        HiLog.info(LABEL_LOG, "MainAbilitySlice onRestoreData");
        Object userName = intentParams.getParam("userName");
        if(userName != null){
            params = (String)userName;
        }
        return true;
    }

    /**
     * 迁移完成的回调
     * @param i
     */
    @Override
    public void onCompleteContinuation(int i) {
        HiLog.info(LABEL_LOG, "MainAbilitySlice onCompleteContinuation");
    }

    /**
     * 迁移过程中失败的回调
     */
    @Override
    public void onRemoteTerminated() {
        HiLog.info(LABEL_LOG, "MainAbilitySlice onRemoteTerminated");
    }

    /**
     * 回迁允许的情况下，远端中断
     * @param errorCode
     */
    @Override
    public void onFailedContinuation(int errorCode) {
        IAbilityContinuation.super.onFailedContinuation(errorCode);
        HiLog.info(LABEL_LOG, "MainAbilitySlice onFailedContinuation");
    }
}
